<?php
namespace app\houtai\controller\system;
use app\houtai\controller\BaseController;
use think\db\Expression;
use Exception;

class SigninController extends BaseController {
  /**
   *  @brief  : 系统管理-每日签到奖励
   *  @return : page
   *  @details: RYPlatformDB.[dbo].[SigninConfig]
   */
  public function configAction() {
    $CHANNELS = $this->GetAdminChannel();
    $conds = [];
    $channel = $this->request->param('channel/d', -1);
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['Channel'][] = ['EQ', $channel];
    } else {
      $conds['Channel'] = ['IN', array_keys($CHANNELS)];
    }
    $list = table('SigninConfig', 'rydb.basic')->where($conds)->order(['Channel', 'DayID'])->paginate();
    return $this->fetch('', ['list' => $list, 'CHANNELS' => $CHANNELS, 'channel' => $channel]);
  }
  /**
   *  @brief  : 更新奖励金币
   *  @return : JSON
   *  @details:
   */
  public function UpdateCoinAction() {

    $id = $this->request->param('id/d', 0);
    $gold = $this->request->param('gold/d', 0);
    
    if ($gold <= 0) {
      return result([], 100, '金币数必须为正整数');
    }
    
    $row = table('SigninConfig', 'rydb.platform')->where('ID', $id)->find();
    if (empty($row)) {
      return result([], 101, "配置[{$id}]不存在");
    }
    
    $eax = table('SigninConfig', 'rydb.platform')->where('ID', $id)->update([
      'RewardGold'  => $gold,
      'UpdateTime'  => new Expression('GETDATE()'),
    ]);

    // 通知游戏服务器
    try {
      $params = [
        'Channel' => $row['Channel'],
        'DayID'   => $row['DayID'],
        'NewGold' => $gold,
        'OldGold' => $row['RewardGold'],
      ];
      $retn = CallGameSrv('OnUpdateSigninConfig', $params);
    } catch (Exception $e) {
      $error = $e->getMessage();
      $errno = $e->getCode();
      return result([], $errno, "更新签到奖励成功, 通知游戏服务器失败[{$error}]");
    }
    return result([], 0);
  }
}
